import { clearCache } from './http'
// 用户认证相关工具函数

// 保存用户信息和token到localStorage
export const saveAuthInfo = (token, user) => {
  localStorage.setItem('token', token)
  localStorage.setItem('user', JSON.stringify(user))
}

// 从localStorage获取token
export const getToken = () => {
  return localStorage.getItem('token')
}

// 从localStorage获取用户信息
export const getUser = () => {
  const user = localStorage.getItem('user')
  return user ? JSON.parse(user) : null
}

// 清除localStorage中的认证信息
export const clearAuthInfo = () => {
  localStorage.clear()
  clearCache()
}

// 检查用户是否已登录
export const isLoggedIn = () => {
  return !!getToken()
}

// 检查用户是否为管理员
export const isAdmin = () => {
  const user = getUser()
  return user && user.role === 'admin'
}

// 设置默认的认证头
export const setAuthHeader = (httpInstance) => {
  const token = getToken()
  if (token) {
    httpInstance.defaults.headers.common['Authorization'] = `Bearer ${token}`
  } else {
    delete httpInstance.defaults.headers.common['Authorization']
  }
}
